package com.example.graphic.service.impl;


import com.example.graphic.AI.AIApiResponse;
import com.example.graphic.AI.AIImageGenerateRequest;
import com.example.graphic.AI.AIImageGenerateResponse;
import com.example.graphic.AI.AIPostersRequest;
import com.example.graphic.service.AIImageService;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * AI图片生成服务实现类
 */
@Slf4j
@Service
public class AIImageServiceImpl implements AIImageService {
    
    private final ObjectMapper objectMapper = new ObjectMapper();
    private final OkHttpClient httpClient;
    
    @Value("${ai.api.base-url:http://192.168.8.122:8001}")
    private String baseUrl;

    @Value("${ai.api.base-url:http://192.168.8.129:8000}")
    private String baseUrl1;

    @Value("${ai.api.endpoint:/api/image/image-to-image}")
    private String endpoint;

    @Value("${ai.api.endpoint:/api/analysis/advanced-image-description}")
    private String endpoint1;

    @Value("${ai.api.endpoint:/generate-poster}")
    private String endpoint2;

    @Value("${ai.api.max-retries:3}")
    private int maxRetries;
    
    @Value("${ai.api.default-strength:0.8}")
    private Double defaultStrength;
    
    public AIImageServiceImpl(OkHttpClient httpClient) {
        this.httpClient = httpClient;
        log.info("AIImageService初始化完成，使用配置的HTTP客户端");
    }
    
    @Override
    public AIImageGenerateResponse generateSimilarImages( AIImageGenerateRequest request) {
        log.info("开始生成相似图片，原始图片URL: {}, 生成数量: {}, prompt: {}", 
                 request.getImage(), request.getNum(), request.getPrompt());
        
        try {
            // 调用第三方AI API
            List<String> generatedImageUrls = callAIApi(request);
            
            log.info("图片生成成功，生成数量: {}", generatedImageUrls.size());
            return AIImageGenerateResponse.success(generatedImageUrls, "图片生成成功");
            
        } catch (Exception e) {
            log.error("图片生成失败，错误信息: {}", e.getMessage(), e);
            return AIImageGenerateResponse.error("图片生成失败: " + e.getMessage(), 500);
        }
    }
    
    /**
     * 调用第三方AI API
     */
    private List<String> callAIApi(AIImageGenerateRequest request) throws IOException {

        // 构建表单参数
        if(request.getPrompt() == null || request.getPrompt().isEmpty()){
            FormBody.Builder formBuilder1 = new FormBody.Builder()
                    .add("image", request.getImage())
                    .add("num", String.valueOf(request.getNum()));

            RequestBody body1 = formBuilder1.build();
            Request httpRequest = new Request.Builder()
                    .url(baseUrl + endpoint1)
                    .post(body1)
                    .addHeader("Content-Type", "application/x-www-form-urlencoded")
                    .build();
            // 发送请求
            try (Response response = httpClient.newCall(httpRequest).execute()) {
                if (!response.isSuccessful()) {
                    throw new IOException("AI API调用失败，HTTP状态码: " + response.code());
                }

                String responseBody = response.body().string();
                log.info("AI API响应: {}", responseBody);

                // 解析响应
                AIApiResponse apiResponse = objectMapper.readValue(responseBody, AIApiResponse.class);

                if (!apiResponse.isSuccess()) {
                    throw new IOException("AI API返回错误: " + apiResponse.getMessage());
                }

                if (apiResponse.getImages() == null || apiResponse.getImages().isEmpty()) {
                    throw new IOException("AI API未返回生成的图片");
                }

                return apiResponse.getImages();
            }
        }
        FormBody.Builder formBuilder = new FormBody.Builder()
                .add("image", request.getImage())
                .add("prompt", request.getPrompt())
                .add("num", String.valueOf(request.getNum()));

        RequestBody body = formBuilder.build();
        Request httpRequest = new Request.Builder()
                .url(baseUrl + endpoint)
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        log.info("调用AI API，URL: {}, 表单参数: image={}, prompt={}, num={}, strength={}",
                baseUrl + endpoint, request.getImage(), request.getPrompt(),
                request.getNum());

        // 发送请求
        try (Response response = httpClient.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("AI API调用失败，HTTP状态码: " + response.code());
            }
            
            String responseBody = response.body().string();
            log.info("AI API响应: {}", responseBody);
            
            // 解析响应
            AIApiResponse apiResponse = objectMapper.readValue(responseBody, AIApiResponse.class);
            
            if (!apiResponse.isSuccess()) {
                throw new IOException("AI API返回错误: " + apiResponse.getMessage());
            }
            
            if (apiResponse.getImages() == null || apiResponse.getImages().isEmpty()) {
                throw new IOException("AI API未返回生成的图片");
            }
            
            return apiResponse.getImages();
        }
    }


    @Override
    public AIImageGenerateResponse postersImages( AIPostersRequest request ) {
        log.info("开始生成相似图片，原始图片URL: {}, 生成样式: {}, prompt: {}",
                request.getImage(), request.getStyle(), request.getPrompt());

        try {
            // 调用第三方AI API
            List<String> generatedImageUrls = aiPosters(request);

            log.info("图片生成成功，生成数量: {}", generatedImageUrls.size());
            return AIImageGenerateResponse.success(generatedImageUrls, "图片生成成功");

        } catch (Exception e) {
            log.error("图片生成失败，错误信息: {}", e.getMessage(), e);
            return AIImageGenerateResponse.error("图片生成失败: " + e.getMessage(), 500);
        }
    }

    /**
     * 调用海报第三方AI API
     */
    private List<String> aiPosters(AIPostersRequest request) throws IOException {
        // 构建表单参数
        FormBody.Builder formBuilder = new FormBody.Builder()
                .add("image", request.getImage())
                .add("prompt", request.getPrompt())
                .add("style", String.valueOf(request.getStyle()));

        RequestBody body = formBuilder.build();
        Request httpRequest = new Request.Builder()
                .url(baseUrl1 + endpoint2)
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        log.info("调用AI API，URL: {}, 表单参数: image={}, prompt={}, style={}",
                baseUrl1 + endpoint2, request.getImage(), request.getPrompt(),
                request.getStyle());

        // 发送请求
        try (Response response = httpClient.newCall(httpRequest).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("AI API调用失败，HTTP状态码: " + response.code());
            }

            String responseBody = response.body().string();
            log.info("AI API响应: {}", responseBody);

            // 解析响应
            AIApiResponse apiResponse = objectMapper.readValue(responseBody, AIApiResponse.class);

            if (!apiResponse.isSuccess()) {
                throw new IOException("AI API返回错误: " + apiResponse.getMessage());
            }

            if (apiResponse.getImages() == null || apiResponse.getImages().isEmpty()) {
                throw new IOException("AI API未返回生成的图片");
            }

            return apiResponse.getImages();
        }
    }
}